package com.myBase.core.facade.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.myBase.core.base.consts.ErrorMsgEnum;
import com.myBase.core.base.consts.ResultData;
import com.myBase.core.dao.GoldcoinActivitycashpoolDao;
import com.myBase.core.dao.GoldcoinDao;
import com.myBase.core.entity.GoldCoinActivityFundInputVo;
import com.myBase.core.entity.Goldcoin;
import com.myBase.core.entity.GoldcoinActivitycashpool;
import com.myBase.core.exception.PlatformException;
import com.myBase.core.facade.service.EBaiGoldCoinInPutService;
import com.myBase.core.facade.service.EBeiGoldCoinActivityCashPoolServiceFacade;
import com.myBase.core.facade.service.GoldcoinActivitycashpoolServiceFacade;

@Service("eBeiGoldCoinActivityCashPoolServiceFacade")
public class EBeiGoldCoinActivityCashPoolServiceFacadeImpl implements EBeiGoldCoinActivityCashPoolServiceFacade {
    private static Logger logger = LoggerFactory.getLogger(EBeiGoldCoinActivityCashPoolServiceFacadeImpl.class);

    @Autowired
    private GoldcoinActivitycashpoolServiceFacade goldcoinActivitycashpoolService;

    @Autowired
    private EBaiGoldCoinInPutService goldcoinService;

    @Autowired
    GoldcoinActivitycashpoolDao goldcoinActivitycashpoolDao;

    @Autowired
    GoldcoinDao goldcoinDao;

    @Override
    public ResultData<HashMap<String, Object>> GoldCoinActivityFundInput(
            GoldCoinActivityFundInputVo goldCoinActivityFundInputVo) {
        logger.info("入金资金传递至ebei系统开始，入参为：" + goldCoinActivityFundInputVo.toString());
        //第一搜索数据库中是否已经存在这个记录
        GoldcoinActivitycashpool goldcoinActivitycashpool = goldcoinActivitycashpoolService
                .getBeanByActivityAndBranchId(goldCoinActivityFundInputVo.getActivityId(),
                        goldCoinActivityFundInputVo.getBranchId());

        //组织返回参数，访问成功
        ResultData<HashMap<String, Object>> resultData;
        if (goldcoinActivitycashpool != null) {
            //如果数据库已经存在这条记录，则直接返回成功的记录
            if (StringUtils.isNotBlank(goldcoinActivitycashpool.getCapitalOrderId())
                    && StringUtils.isNotBlank(goldCoinActivityFundInputVo.getCapitalOrderId())
                    && (goldCoinActivityFundInputVo.getCapitalOrderId()
                            .equals(goldcoinActivitycashpool.getCapitalOrderId()))) {
                resultData = new ResultData<HashMap<String, Object>>(ErrorMsgEnum.SUCCESS.getCode(),
                        "入金已经成功，本次为重复调用" + " 金额为：" + goldCoinActivityFundInputVo.getSumCash().toString());
                logger.info("入金成功，本次为重复调用" + " 金额为：" + goldCoinActivityFundInputVo.getSumCash().toString());
                return resultData;
            }
            //如果存在则修改数据并保存
            logger.info("已经存在该活动的入金记录，增加总额和可发行额");
            goldcoinActivitycashpool.setSumcash(goldCoinActivityFundInputVo.getSumCash().toString());
            goldcoinActivitycashpool.setCanusecash(goldCoinActivityFundInputVo.getCanUseCash().toString());
            goldcoinActivitycashpool.setBranchid(goldCoinActivityFundInputVo.getBranchId());
            goldcoinActivitycashpool.setCapitalOrderId(goldCoinActivityFundInputVo.getCapitalOrderId());
            goldcoinActivitycashpool.setRemarks("入金：" + goldcoinActivitycashpool.getSumcash());
        } else//否则直接保存
        {
            logger.info("尚未存在该活动的入金记录，新增记录");
            goldcoinActivitycashpool = new GoldcoinActivitycashpool();//从新实例化
            goldcoinActivitycashpool.setActivityid(Integer.valueOf(goldCoinActivityFundInputVo.getActivityId()));
            goldcoinActivitycashpool.setActivityname(goldCoinActivityFundInputVo.getActivityName());
            goldcoinActivitycashpool.setBegin(goldCoinActivityFundInputVo.getBegin());
            goldcoinActivitycashpool.setEnd(goldCoinActivityFundInputVo.getEnd());
            goldcoinActivitycashpool.setSumcash(goldCoinActivityFundInputVo.getSumCash().toString());
            goldcoinActivitycashpool.setCanusecash(goldcoinActivitycashpool.getSumcash());
            goldcoinActivitycashpool.setFreezecash("0.00");
            goldcoinActivitycashpool.setBranchid(goldCoinActivityFundInputVo.getBranchId());
            goldcoinActivitycashpool.setCapitalOrderId(goldCoinActivityFundInputVo.getCapitalOrderId());
            goldcoinActivitycashpool.setRemarks("入金：" + goldcoinActivitycashpool.getSumcash());
        }

        try {
            goldcoinActivitycashpoolService.saveOrUpdateBySelf(goldcoinActivitycashpool);
            resultData = new ResultData<HashMap<String, Object>>(ErrorMsgEnum.SUCCESS.getCode(),
                    "入金成功，" + " 金额为：" + goldCoinActivityFundInputVo.getSumCash().toString());
            logger.info("入金成功，" + " 金额为：" + goldCoinActivityFundInputVo.getSumCash().toString());
        } catch (Exception e) {
            resultData = new ResultData<HashMap<String, Object>>(ErrorMsgEnum.ERROR.getCode(),
                    "入金失败，" + " 金额为：" + goldCoinActivityFundInputVo.getSumCash().toString() + ";" + e.getMessage());
            logger.info("入金失败，" + " 金额为：" + goldCoinActivityFundInputVo.getSumCash().toString() + ";" + e.getMessage());
        }
        logger.info("入金资金传递至ebei系统结束");
        return resultData;
    }

    // 每一个金币活动进行结算
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public int handleSettlement(BigDecimal leftAmount, BigDecimal totalAmount, Goldcoin goldcoin)
            throws PlatformException {
        logger.info("处理金币结算数据开始");
        // 活动ID
        Integer activityId = goldcoin.getGoldcoinactivity();
        // 更新goldcoin_activitycashpool表金币结算数据
        int count = goldcoinActivitycashpoolDao.updateSettlement(leftAmount, totalAmount, activityId);
        if (count != 1) {
            logger.info("更新goldcoin_activitycashpool表金币相关数据失败");
            throw new PlatformException("更新goldcoin_activitycashpool表金币相关数据失败");
        }
        // 更新gold_coin表金币状态为结算状态  09：已结算
        Integer id = Integer.valueOf(goldcoin.getId());
        count = goldcoinDao.updateStatusForSettlement(id);
        if (count != 1) {
            logger.info("更新gold_coin表金币状态为结算状态失败");
            throw new PlatformException("更新gold_coin表金币状态为结算状态失败");
        }
        logger.info("处理金币结算数据结束");
        return count;
    }

    @Override
    public HashMap<String, Object> getEBeiActivitycashpoolCanUseCash(Integer activityId) {
        return goldcoinActivitycashpoolService.getGoldCoinActivitycashpoolCanUseCash(activityId);
    }

}
